package com.example.incrementaupdatelib;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.incrementalupdate.util.ApkUtil;
import com.example.incrementalupdate.util.PatchUtil;
import com.example.incrementalupdate.util.SignUtil;

import java.io.File;

public class MainActivity extends AppCompatActivity {
    private final String TAG = MainActivity.this.getClass().getSimpleName();
    private final Handler handler = new Handler(Looper.getMainLooper(), msg -> {
        if (msg.what == 0x111) {
            File file = (File) msg.obj;
            UriparseUtils.installApk(this, file);
        }
        return false;
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.btn_compose).setOnClickListener(v -> {
            patch();
        });
        findViewById(R.id.button).setOnClickListener(v -> {
            String apkMd5 = SignUtil.getMd5ByPath(ApkUtil.getSourceApkPath(this));
            Log.e(TAG, "当前运行apk的md5值:" + apkMd5);
        });
        TextView textView = findViewById(R.id.textView2);
        textView.setText(BuildConfig.DEBUG ? "测试版本" : "正式版本");
    }

    private void patch() {
        new Thread(() -> {
            //获取现在运行的apk路径
            String oldApk = ApkUtil.getSourceApkPath(this);
            Log.e(TAG, "第一步成功==>获取现在运行的apk路径");
            // 获取拆分包的路径
            String patch = new File(getExternalFilesDir("app"), "patch").getAbsolutePath();
            Log.e(TAG, "第二步成功==>获取拆分包的路径");
            // 获取合成之后的新apk的路径
            String output = createNewApk().getAbsolutePath();
            Log.e(TAG, "第三步成功==>获取合成之后的新apk的路径");
            // 合成新apk
            PatchUtil.bsPath(oldApk, patch, output);
            Log.e(TAG, "第四步成功==>合成新apk");
            check(output);
            Message obtain = Message.obtain();
            obtain.what = 0x111;
            obtain.obj = new File(output);
            handler.sendMessage(obtain);
        }).start();
    }

    /**
     * 合成的最新的md5值和最新apk的md5校验
     */
    private void check(String newApkPath){
        String apkMd5 = SignUtil.getMd5ByPath(newApkPath);
        Log.e(TAG, "合成的apk的md5值：" + apkMd5);
    }

    private File createNewApk() {
        return new File(getExternalFilesDir("app"), "new2.apk");
    }
}